﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;
using System.Data.SqlClient;

namespace CivilleWebRole
{
    public partial class EditReward : System.Web.UI.Page
    {
        public const string REWARD_LOGO_PATH = "htt" + "p://civillehostedservices.cloudapp.net/Logo/Rewards/";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("~/NotAuthorized.aspx");
            }
        }

        protected void Calendar_SelectionChanged(object sender, EventArgs e)
        {
            SelectedExpiringDate.Text = ExpiringDateCalendar.SelectedDate.ToShortDateString();
        }

        protected void SaveRewardButtonClick(object sender, EventArgs e)
        {
            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = connection.CreateCommand();
            SqlCommand getStakeholderIDCommand = connection.CreateCommand();
            getStakeholderIDCommand.CommandText = "SELECT ID FROM Stakeholder WHERE Name = '" + User.Identity.Name + "'";
            connection.Open();
            int stakeholderID = (int)getStakeholderIDCommand.ExecuteScalar();

            foreach (GridViewRow row in TasksGridView.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("TaskSelector");
                if (cb != null && cb.Checked)
                {
                    int taskID =
                        Convert.ToInt32(TasksGridView.DataKeys[row.RowIndex].Value);
                    int count = Convert.ToInt32(((TextBox)row.FindControl("CountTxt")).Text);

                    if (this.FileUpload.HasFile)
                    {
                        if (isLogoSaved())
                        {
                            String id = (Convert.ToInt32(getLastId()) + 1).ToString();
                            String fileExtension = System.IO.Path.GetExtension(FileUpload.FileName).ToLower();
                            command.CommandText = "INSERT INTO [Reward] ([StakeholderID], [Title], [Description], [TaskID], [Count], [ExpiringDate], [Logo]) VALUES ('"
                               + stakeholderID + "', '" + TitleTxt.Text + "', '" + DescriptionTxt.Text + "', '" + taskID + "', '" + count + "', '" + ExpiringDateCalendar.SelectedDate + "', '" + REWARD_LOGO_PATH + id + fileExtension + "')";
                        }
                    }
                    else
                    {
                        String path = "default.jpg";
                        command.CommandText = "INSERT INTO [Reward] ([StakeholderID], [Title], [Description], [TaskID], [Count], [ExpiringDate], [Logo]) VALUES ('"
                               + stakeholderID + "', '" + TitleTxt.Text + "', '" + DescriptionTxt.Text + "', '" + taskID + "', '" + count + "', '" + ExpiringDateCalendar.SelectedDate + "', '" + REWARD_LOGO_PATH + path + "')";
                    }
                }
            }

            command.ExecuteNonQuery();
            connection.Close();
        }

        protected bool isLogoSaved()
        {
            String path = "";
            if (this.FileUpload.HasFile)
            {
                if (CheckFileType(FileUpload.FileName))
                {
                    String id = (Convert.ToInt32(getLastId()) + 1).ToString();
                    path = Server.MapPath("Logo/Rewards/" + id + System.IO.Path.GetExtension(FileUpload.FileName).ToLower());
                }
                else
                {
                    StatusLabel.Text = "The selected image is not valid!";
                    return false;
                }
            }

            try
            {
                this.FileUpload.SaveAs(path);
            }
            catch (Exception ex)
            {
                StatusLabel.Text = "Could not save the logo!";
                return false;
            }

            return true;
        }

        protected String getLastId()
        {
            String connectionString = ConfigurationManager.ConnectionStrings["CivilleConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);

            SqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT IDENT_CURRENT('Reward')";
            connection.Open();
            String rsIdentity = command.ExecuteScalar().ToString();
            connection.Close();
            return rsIdentity;
        }

        protected bool checkUploadedFile(FileUpload fu)
        {
            if (CheckFileType(fu.FileName))
            {
                if (fu.PostedFile.ContentLength < 40960)
                {
                    return true;
                }
            }
            return false;
        }

        bool CheckFileType(string fileName)
        {
            string ext = Path.GetExtension(fileName);
            switch (ext.ToLower())
            {
                case ".gif":
                    return true;
                case ".png":
                    return true;
                case ".jpg":
                    return true;
                case ".jpeg":
                    return true;
                default:
                    return false;
            }
        }
    }
}